package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"ruoyi-hello/app/domain"
	"ruoyi-hello/app/sys/service"
	"ruoyi-hello/common"
	"ruoyi-hello/utils"
	"ruoyi-hello/utils/R"
	"ruoyi-hello/utils/error"
)

// 后台获取 首页数据

func IndexData() {
	//
}

// IndexHandler 测试代码
func IndexHandler(context *gin.Context) {
	context.JSON(http.StatusOK, R.ReturnSuccess("Hello ruoyi go"))
}

func LoginHandler(context *gin.Context) {
	var loginParam domain.LoginReq
	err := context.ShouldBindJSON(&loginParam)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFail(error.BusstionError{Code: http.StatusBadRequest, Msg: "用户名密码错误"}))
	} else {
		userLogin, err := service.Loign(&loginParam)
		if err.Code != error.Ok.Code {
			context.JSON(http.StatusOK, R.ReturnFail(error.BusstionError{Code: http.StatusBadRequest, Msg: "用户名密码错误"}))
		} else {
			tokenString, errToken := utils.CreateToken(userLogin.UserName, userLogin.UserId, userLogin.DeptId)
			if errToken != nil {
				context.JSON(http.StatusOK, R.ReturnFail(error.BusstionError{Code: http.StatusInternalServerError, Msg: "系统内部错误"}))
			}
			context.JSON(http.StatusOK, R.ReturnSuccess(tokenString))
		}
	}
}
func GetLoginUserInfoHandler(context *gin.Context) {
	userId, _ := context.Get(common.USERID)
	if userId.(float64) <= 0 {
		context.JSON(http.StatusOK, R.ReturnFail(error.BusstionError{Code: http.StatusBadRequest, Msg: "用户数据有异常，请从新登录"}))
	}
	sysUser := service.FindUserById(int(userId.(float64)))
	if sysUser.UserId <= 0 {
		context.JSON(http.StatusOK, R.ReturnFail(error.BusstionError{Code: http.StatusBadRequest, Msg: "用户信息不存在，请从新登录"}))
	}
	roles, roleIds := service.GetRolePermission(sysUser)
	permissions := service.GetMenuPermission(sysUser, roleIds)
	context.JSON(http.StatusOK, gin.H{
		"code":        http.StatusOK,
		"roles":       roles,
		"user":        sysUser,
		"permissions": permissions,
	})
}
